'use strict'

const { Controller } = require('egg')

class HomeController extends Controller {
  async index() {
    const { ctx, service } = this
    ctx.body = await service.index.find('wivwiv')
  }

  async create() {
    const { ctx, service } = this
    ctx.body = 'create'
  }

  async update() {
    const { ctx } = this
    ctx.isAdmin()
    const { host, port, title, smtp_host, smtp_port, smtp_secure, smtp_user, smtp_password, sms_url, sms_account, sms_token, sms_model } = ctx.request.body
    const data = {
      host,
      port,
      title,
      smtp_host,
      smtp_port,
      smtp_secure,
      smtp_user,
      smtp_password,
      sms_url,
      sms_account,
      sms_token,
      sms_model,
    }
    require('fs').writeFileSync(require('path').join(__dirname, '../../config/config.json'), JSON.stringify(data, null, 2))
    ctx.body = {}
  }

  async destroy() {
    const { ctx, service } = this
    ctx.body = 'destroy'
  }

  /**
   * 我的服务器信息
   * @returns {Promise<void>}
   */
  async status() {
    const { ctx, service } = this
    ctx.isLogin()
    const user = ctx.user._id
    ctx.body = await service.index.status(user)
  }

  async statusAdmin() {
    const { ctx, service } = this
    ctx.isAdmin()
    ctx.body = await service.index.status()
  }

  async showConfig() {
    const { ctx, service } = this
    ctx.isAdmin()
    ctx.body = require('../../config/config')
  }

  async updateConfig() {
    const { ctx } = this
    ctx.isAdmin()
    const data = ctx.safeLoader('host,port,title,smtp_host,smtp_port,smtp_secure,smtp_user,smtp_password,sms_url,sms_account,sms_token,sms_model')
    const old = require('../../config/config')
    Object.keys(old).forEach((key) => {
      data[key] = data[key] || old[key]
    })
    require('fs').writeFileSync('../../config/config.json', JSON.stringify(data, null, 2))
    console.log(JSON.stringify(data, null, 2))
    ctx.body = {}
  }
}

module.exports = HomeController
